<template>
  <div class="merchant-list">
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.name" placeholder="请输入商家名称" clearable class="w-60" />
        </el-form-item>
        <!-- <el-form-item label="商家标题">
                                                <el-input v-model="searchForm.title" placeholder="请输入商家标题" clearable class="w-60" />
                                            </el-form-item>
                                            <el-form-item label="联系电话">
                                                <el-input v-model="searchForm.phone" placeholder="请输入联系电话" clearable class="w-60" />
                                            </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" style="margin-left: 30px" v-has="'community:save'">新增商家</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border style="width: 100%;margin-top:15px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="商家名称" />
      <el-table-column prop="title" label="商家标题" />
      <el-table-column prop="imageUrl" label="商家图片" width="120">
        <template #default="{ row }">
          <el-image v-if="row.imageUrl" style="width: 80px; height: 80px" :src="row.imageUrl"
            :preview-src-list="[row.imageUrl]" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="商家地址" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <!-- <el-table-column prop="description" label="店铺介绍" show-overflow-tooltip /> -->
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="text" v-has="'community:update'" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" v-has="'community:delete'"
            @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增商家' : '编辑商家'" :visible.sync="dialogVisible" width="80%"
      @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="dialog_height">
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="商家标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入商家标题" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <div class="flex_contents">
            <el-rate v-model="form.rating" :max="5" :texts="['1分', '2分', '3分', '4分', '5分']" show-text />
          </div>
        </el-form-item>
        <!-- <el-form-item label="评分文本" prop="ratingText">
          <el-input v-model="form.ratingText" placeholder="请输入评分文本" />
        </el-form-item>
        <el-form-item label="评价数量" prop="reviewCount">
          <el-input-number v-model="form.reviewCount" :min="0" placeholder="请输入评价数量" />
        </el-form-item> -->
        <el-form-item label="营业时间">
          <el-col :span="11">
            <el-form-item prop="startTime">
                 <el-time-select :picker-options="{
      start: '00:00',
        step: '00:15',
        end: '23:59'
    }" v-model="form.startTime" value-format="HH:mm" placeholder="开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
                 <el-time-select :picker-options="{
      start: '00:00',
        step: '00:15',
        end: '23:59'
    }"  v-model="form.endTime" value-format="HH:mm" placeholder="结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="商家封面图" prop="imageUrl">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleUploadSuccess" :before-upload="beforeUpload">
            <img v-if="form.imageUrl" :src="form.imageUrl" class="uploaded-image" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus"></i>
              <div class="upload-text">点击上传商家图片</div>
            </div>
          </el-upload>
          <!-- <div class="form-tip">建议尺寸：200x200px，支持jpg、png格式</div> -->
        </el-form-item>
        <el-form-item label="商家轮播图" prop="imageUrl">
          <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
            :on-success="handleIconSuccess1" :before-upload="beforeUpload">
            <div class="flex_flex">
              <div v-for="item,index in form.carouselImages" :key="index" class="image-item">
                <img :src="item" class="uploaded-image" />
                <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
              </div>
              <div class="upload-placeholder">
                <i class="el-icon-plus"></i>
                <div class="upload-text">点击上传图片</div>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入商家地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="标签以逗号(，)隔开" />
        </el-form-item>
        <el-form-item label="店铺介绍" prop="description">
          <EditorBar style="width: 100%" v-model="form.description" :catchData="catchDataAgreement"></EditorBar>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import EditorBar from "@/components/WangEnduit.vue";

export default {
  name: 'MerchantList',
  components: {
    EditorBar
  },
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        name: '',
        title: '',
        phone: ''
      },
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 表格数据
      tableData: [],
      loading: false,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      uploadUrl: '', // 上传地址
      form: {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: '',
        rating: 0,
        // ratingText: '',
        // reviewCount: 0,
        tags: '',
        startTime: '09:30',
        endTime: '21:30',
        carouselImages: []
      },
      // 表单校验规则
      rules: {
        rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
        ratingText: [{ required: true, message: '请输入评分文本', trigger: 'blur' }],
        reviewCount: [{ required: true, message: '请输入评价数量', trigger: 'change' }],
        name: [
          { required: true, message: '请输入商家名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入商家标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入商家地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleDeleteImage(index) {
      this.form.carouselImages.splice(index, 1)
    },
    // 图片上传成功回调
    async handleIconSuccess1(res) {
      this.form.carouselImages.push(res.result.filePath)
    },
    //基本信息富文本编辑
    catchDataAgreement(val) {
      this.form.description = val;
    },
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const { data } = await this.$api.getMerchantList({
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm
          }
        })
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取商家列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        title: '',
        phone: ''
      }
      this.handleSearch()
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.form = {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: '',
        rating: 0,
        // ratingText: '',
        // reviewCount: 0,
        tags: '',
        startTime: '09:30',
        endTime: '21:30',
        carouselImages: []
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row, tags: row.tags.join('，'), }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该商家吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteMerchant(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
        }
      }).catch(() => { })
    },

    // 上传相关
    handleUploadSuccess(res) {
      this.form.imageUrl = res.result.filePath

    },

    beforeUpload(rawFile) {
      // const imgSize = rawFile.size / 1024 / 1024 < 1000
      // const imgType = ['image/jpeg', 'image/png', 'image/gif']
      // if (!imgType.includes(rawFile.type))
      //   message.notifyWarning('上传图片不符合所需的格式！')
      // if (!imgSize) message.notifyWarning(`上传图片大小不能超过 1000M！`)
      // return imgType.includes(rawFile.type) && imgSize
    },

    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.form,
              tags: this.form.tags.split('，'),
              // iconUrl: this.iconUploadUrl,
              // banner: this.bannerUploadUrl
            }
            if (this.dialogType === 'add') {
              await this.$api.addMerchant(params)
              this.$message.success('新增成功')
            } else {
              await this.$api.updateMerchant(params)
              this.$message.success('编辑成功')
            }
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            console.error(this.dialogType === 'add' ? '新增失败：' : '编辑失败：', error)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
      this.form = {
        name: '',
        title: '',
        imageUrl: '',
        address: '',
        phone: '',
        description: ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
.dialog_height{
    // height: 50vh;
    // overflow: hidden;
    // overflow-y: auto;
}
.image-item {
  position: relative;
}

.delete-image {
  position: absolute;
  bottom: 15px;
  right: 0px;
  width: 100%;
  height: 20px;
  font-size: 14px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  cursor: pointer;
  z-index: 1000;
  line-height: 20px;
}

.flex_flex {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.text-center {
  text-align: center;
}

.image-uploader {
  .uploaded-image {
    width: 140px;
    height: 140px;
    object-fit: cover;
    border-radius: 4px;
  }

  .upload-placeholder {
    width: 140px;
    height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409EFF;
    }

    .el-icon-plus {
      font-size: 28px;
      color: #8c939d;
    }

    .upload-text {
      font-size: 12px;
      color: #8c939d;
      margin-top: 8px;
    }
  }
}

.merchant-list {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.flex_contents {
  height: 42px;
  display: flex;
  align-items: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>